import React, { useRef, useState } from 'react';
import { View, Button, Camera, Image } from '@tarojs/components';
import './index.less';
import TitleBar from '@/src/components/titleBar';
import store from '@/src/store';
import { observer } from 'mobx-react-lite';
import Taro from '@tarojs/taro';

const TakePhoto: React.FC = () => {
  const cameraRef = useRef<any>(null);
  const [photo, setPhoto] = useState<string>('');

  const takePhoto = async () => {
    if (!cameraRef.current) return;
    try {
      const { tempImagePath } = await cameraRef.current.takePhoto({
        quality: 'high',
      });
      setPhoto(tempImagePath);
      // TODO: 调用识别接口
    } catch (err) {
      console.error('拍照失败', err);
    }
  };

  // 点击标题栏返回事件
  const onBackClick = () => {
    Taro.reLaunch({ url: '/pages/home/index' });
  };

  return (
    <View
      className="scan-page"
      style={{
        paddingTop: `${store.commonStore.pageAreaTop}rpx`,
      }}
    >
      <TitleBar
        showLeftBack={true}
        title="拍照识别"
        theme="dark"
        onBack={onBackClick}
      ></TitleBar>
      {/* 摄像头预览区 */}
      {!photo && (
        <View className="camera-wrapper">
          <Camera
            ref={cameraRef}
            devicePosition="back"
            flash="off"
            className="camera"
          />
          {/* —— 白色引导框 —— */}
          <Image
            src="https://file.linkcook.cn/image/wineMiniProgram/imgs/scan/ciga.png"
            className="guide-box"
          />
          <View className="takePh-desc">请将雪茄标置于虚线框内拍照</View>
          {/* —— 底部快门按钮 —— */}
          <View className="shutter-bar">
            <Image
              src="https://file.linkcook.cn/image/wineMiniProgram/imgs/scan/takePh.png"
              className="shutter-btn"
              onClick={takePhoto}
            />
            <Image
              src="https://file.linkcook.cn/image/wineMiniProgram/imgs/scan/photo.png"
              className="selectPh"
            ></Image>
          </View>
        </View>
      )}

      {/* 拍完后显示结果 */}
      {photo && (
        <View className="result">
          <Image src={photo} mode="widthFix" className="result-img" />
          <Button onClick={() => setPhoto('')}>重拍</Button>
        </View>
      )}
    </View>
  );
};

export default observer(TakePhoto);
